package indi.zhifa.core.common.web.aop;

import com.alibaba.fastjson2.JSON;
import indi.zhifa.core.common.util.CommonUtil;
import indi.zhifa.core.common.web.entity.exception.ServiceException;
import indi.zhifa.core.common.web.entity.response.RestResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.sql.SQLException;
import java.util.List;
import java.util.Set;


/**
 * 统一的异常捕获类
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandle {

    /**
     * 统一异常处理方法
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public RestResponse handle(Exception e){
        log.debug(e.getMessage());
        if(e instanceof ServiceException){//业务异常
            ServiceException serviceException=(ServiceException)e;
            return RestResponse.error(serviceException.getCode(),serviceException.getMessage());
        }else if(e instanceof SQLException){//数据库异常
            SQLException serviceException= (SQLException)e;
            serviceException.printStackTrace();
            return RestResponse.error(serviceException.getErrorCode(),"发生sql错误，请联系管理员");
        }else if(e instanceof BindException){//数据库异常
            //打印校验住的所有的错误信息
            StringBuilder sb = new StringBuilder("参数错误：[");
            List<ObjectError> list = ((BindException) e).getAllErrors();
            for (ObjectError item : list) {
                sb.append("字段").append(item.getCodes()[0]).append(item.getDefaultMessage()).append(',');
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append(']');
            return RestResponse.error(sb.toString());
        }else if (e instanceof MissingServletRequestParameterException) {
            StringBuilder sb = new StringBuilder();
            MissingServletRequestParameterException mex = (MissingServletRequestParameterException)e;
            sb.append("参数缺失 "+mex.getParameterName()).append(";");
            return RestResponse.error(sb.toString());
        } else if(e instanceof HttpRequestMethodNotSupportedException){
            StringBuilder sb = new StringBuilder();
            HttpRequestMethodNotSupportedException hrmnsEx = (HttpRequestMethodNotSupportedException)e;
            sb.append("该接口不支持 "+hrmnsEx.getMethod()+", 请使用"+ JSON.toJSONString(hrmnsEx.getSupportedMethods()));
            return RestResponse.error(sb.toString());
        }else if(e instanceof HttpMessageNotReadableException httpMessageNotReadableException){
            StringBuilder sb = new StringBuilder();
            HttpMessageNotReadableException ex = (HttpMessageNotReadableException)e;
            sb.append("消息无法读取,详细信息为"+ex.getLocalizedMessage());
            return RestResponse.error(sb.toString(),httpMessageNotReadableException.getMessage());
        }else if(e instanceof MaxUploadSizeExceededException){
            MaxUploadSizeExceededException maxUploadSizeExceededException = (MaxUploadSizeExceededException)e;
            return RestResponse.error("上传文件大小超出上限"+  CommonUtil.roundDouble(maxUploadSizeExceededException.getMaxUploadSize() / (1024.0*1024.0),2)  + "MB");
        }
        else if(e instanceof DuplicateKeyException dpKeyEx){
            StringBuilder sb = new StringBuilder();
            sb.append("好逆天，数据库主键重复啦，快联系程序员修BUG");
            return RestResponse.error(sb.toString(),dpKeyEx.getMessage());
        }else if(e instanceof NullPointerException nullPointerException){
            StringBuilder sb = new StringBuilder();
            sb.append("很不幸，系统发生了空指针异常，请联系程序员修BUG！");
            String message = CommonUtil.getMessage(e);
            log.error(message);
            return RestResponse.error(sb.toString(),nullPointerException.getMessage());
        }else if(e instanceof DataIntegrityViolationException sqlEx){
            StringBuilder sb = new StringBuilder();
            sb.append("发生sql错误");
            sb.append(sqlEx.getMessage());
            String message = CommonUtil.getMessage(e);
            log.error(message);
            return RestResponse.error(sb.toString());
        }else if(e instanceof HttpMediaTypeNotSupportedException httpMediaTypeNotSupportedException){
            StringBuilder sb = new StringBuilder();
            sb.append("当前请求不支持"+httpMediaTypeNotSupportedException.getContentType()+"类型的请求");
            return RestResponse.error(sb.toString());
        }else if(e instanceof NoResourceFoundException noResourceFoundException){
            StringBuilder sb = new StringBuilder();
            sb.append("请求的链接不存在"+noResourceFoundException.getResourcePath());
            return RestResponse.error(sb.toString());
        }
        else{//其他系统异常
            return otherException(e);
        }
    }

    @ExceptionHandler(value = {ConstraintViolationException.class, MethodArgumentNotValidException.class, BindException.class})
    @ResponseBody
    public RestResponse<Object> argumentValidException(HttpServletRequest req, Exception ex) {
        StringBuilder sb = new StringBuilder("参数验证失败:");
        //Controller上 @Valid + 校验标签(例如@NotBlank()) 在方法形参 中直接校验参数抛出异常
        if(ex instanceof ConstraintViolationException){
            ConstraintViolationException ce = (ConstraintViolationException) ex;
            Set<ConstraintViolation<?>> errors = ce.getConstraintViolations();
            errors.forEach(error->{
                sb.append(error.getMessage()).append(";");
            });
            //@Valid + @RequestBody 校验出错抛出的异常
        }else if(ex instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException me = (MethodArgumentNotValidException) ex;
            List<ObjectError> errors = me.getBindingResult().getAllErrors();
            errors.forEach(error->{
                sb.append(error.getDefaultMessage()).append(";");
            });
            //@Valid User user校验实体类中字段出错时抛出的异常
        }else if (ex instanceof BindException){
            BindException be = (BindException) ex;
            List<ObjectError> errors = be.getAllErrors();
            errors.forEach(error->{
                sb.append(error.getDefaultMessage()).append(";");
            });
        }
        log.error("系统出现未知异常,请联系管理员2", ex);
        return RestResponse.error(sb.toString());
    }

    /**
     * 其他的系统异常
     * @param
     * @return
     */
    private static RestResponse otherException(Exception e){

        if(e instanceof SQLException sqlException){
            String message = CommonUtil.getMessage(e);
            log.error(message);
            return RestResponse.error("系统出现未知sql异常, code = "+sqlException.getErrorCode()+",请联系管理员",sqlException.getLocalizedMessage());
        }

        //插入数据库
        //如果更严重给出提示预警
        String message = CommonUtil.getMessage(e);
        log.error(message);
        return RestResponse.error("系统出现未知异常,请联系管理员");
    }

}
